import {defineStore} from 'pinia'
import {reqGetCode, reqLogout, reqUserInfo, reqUserLogin, reqUserRegister} from '@/api'
import {getToken, removeToken, setToken} from '@/libs/token'
import {UserInfoType} from './types'
import {LoginDataType, RegisterDataType} from '@/api/types'
//login与register模块的仓库
export const useUserStore = defineStore('user', {
    state: () => ({
        //验证码
        code: '',
        //token令牌
        token: getToken(),
        //用户信息
        userInfo: <UserInfoType>{}
    }),
    getters: {},
    actions: {
        //获取验证码
        async getCode(phone: string) {
            let result = await reqGetCode(phone)
            if (result.code == 200) {
                this.code = result.data
                return 'ok'
            } else {
                return Promise.reject(new Error('fail'))
            }
        },
        //用户注册
        async userRegister(user: RegisterDataType) {
            let result = await reqUserRegister(user)
            if (result.code == 200) {
                return 'ok'
            } else {
                return Promise.reject(new Error('fail'))
            }
        },
        //用户登录
        async userLogin(user: LoginDataType) {
            let result = await reqUserLogin(user)
            if (result.code == 200) {
                this.token = result.data.token
                setToken(result.data.token)
                return 'ok'
            } else {
                return Promise.reject(new Error('fail'))
            }
        },
        //获取用户信息
        async getUserInfo() {
            let result = await reqUserInfo()
            if (result.code == 200) {
                this.userInfo = result.data
                return 'ok'
            } else {
                return Promise.reject(new Error('fail'))
            }
        },
        //退出登录
        async userLogout() {
            let result = await reqLogout()
            if (result.code == 200) {
                this.token = ''
                this.userInfo = <UserInfoType>{}
                removeToken()
                return 'ok'
            } else {
                return Promise.reject(new Error('fail'))
            }
        }
    }
})
